package org.stvd.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.task.TaskDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Roles;
import org.stvd.entities.admin.Users;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.RolesService;
import org.stvd.service.admin.UsersService;

@Component
public class DepAndUserHolder {

    @Autowired
    private UsersService usersService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    protected RepositoryService repositoryService;

    // 声明静态变量，为了之后调用service
    public static DepAndUserHolder depAndUserHolder;

    @PostConstruct
    public void init() {
        depAndUserHolder = this;
        depAndUserHolder.usersService = this.usersService;
        depAndUserHolder.departmentService = this.departmentService;
        depAndUserHolder.rolesService = this.rolesService;
        depAndUserHolder.repositoryService = this.repositoryService;
    }

    public static String getUserMaxAuthDepId(String userId, String guid) {
        String maxAuthDepId = "";
        Department department = getUserMaxAuthDep(userId, guid);
        if (department != null) {
            maxAuthDepId = department.getDepId();
        }
        return maxAuthDepId;
    }

    // 根据用户ID获取用户最大机构
    public static Department getUserMaxAuthDep(String userId, String guid) {
        Department maxAuthDep = null;
        List<Department> departmentList = getUserDepInfo(userId, guid);
        if (departmentList != null && departmentList.size() > 0) {
            for (Department department : departmentList) {
                if (maxAuthDep == null) {
                    maxAuthDep = department;
                    continue;
                }
                if (maxAuthDep.getInnerCode().length() > department.getInnerCode().length()) {
                    maxAuthDep = department;
                }
            }
        }
        return maxAuthDep;
    }

    // 根据用户ID获取用户最小机构
    public static Department getUserMinAuthDep(String userId, String guid) {
        Department minAuthDep = null;
        List<Department> departmentList = getUserDepInfo(userId, guid);
        if (departmentList != null && departmentList.size() > 0) {
            for (Department department : departmentList) {
                if (minAuthDep == null) {
                    minAuthDep = department;
                    continue;
                }
                if (minAuthDep.getInnerCode().length() < department.getInnerCode().length()) {
                    minAuthDep = department;
                }
            }
        }
        return minAuthDep;
    }

    /**
     * 根据用户ID获取用户所属机构列表
     * 
     * @return
     */
    public static List<Department> getUserDepInfo(String userId, String guid) {
        try {
            if (StringUtil.isEmpty(guid)) {
                guid = Consts.GUID;
            }
            List<Department> departmentList = new ArrayList<Department>();
            List<Department> tmpList = depAndUserHolder.departmentService.findDepByUid(userId, guid);
            if (tmpList != null && tmpList.size() > 0) {
                departmentList = new ArrayList<>();
                for (Department department : tmpList) {
                    if (guid.equals(department.getGuid())) {
                        departmentList.add(department);
                    }
                }
                return departmentList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户角色列表
     * 
     * @return
     */
    public static List<Roles> getUserRoleInfo(String userId, String guid, String depId) {
        try {
            List<Roles> roleList = getUserRoleInfo(userId, guid);
            if (roleList != null && roleList.size() > 0) {
                Iterator<Roles> it = roleList.iterator();
                while (it.hasNext()) {
                    Roles role = it.next();
                    if (!depId.equals(role.getDepId())) {
                        it.remove();
                    }
                }
            }
            return roleList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前登录用户角色列表
     * 
     * @return
     */
    public static List<Roles> getUserRoleInfo(String userId, String guid) {
        try {
            if (StringUtil.isEmpty(guid)) {
                guid = Consts.GUID;
            }
            List<Roles> roleList = new ArrayList<Roles>();
            List<Roles> tmpList = depAndUserHolder.rolesService.getRolesByUserId(userId, guid);
            if (tmpList != null && tmpList.size() > 0) {
                roleList = new ArrayList<>();
                for (Roles roles : tmpList) {
                    if (guid.equals(roles.getGuid())) {
                        roleList.add(roles);
                    }
                }
                return roleList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getUserRoleDepth(String userId, String guid) {
        String userRole = "";
        // 获取用户的内置角色信息
        String depId = DepAndUserHolder.getUserMaxAuthDepId(userId, guid);
        // 当前用户在该机构的用户角色
        List<Roles> userRoleList = DepAndUserHolder.getUserRoleInfo(userId, Consts.GUID, depId);
        if (userRoleList != null && userRoleList.size() > 0) {
            List<String> depList = new ArrayList<String>();
            depList.add(depId);
            for (int i = 0; i < userRoleList.size(); i++) {
                Roles role = userRoleList.get(i);
                if ("ROLE_MANAGE".equals(role.getRoleCode())) {
                    userRole = "ROLE_MANAGE";
                    break;
                } else if ("ROLE_DEP_LEADER".equals(role.getRoleCode())) {
                    userRole = "ROLE_DEP_LEADER";
                    break;
                } else if ("ROLE_DEP_STAFF".equals(role.getRoleCode())) {
                    userRole = "ROLE_DEP_STAFF";
                    break;
                }
            }
        }
        return userRole;
    }
    //审批节点用户名拼接字符串
    public static String getApproveUserTaskNameString(String usesString) {
		String usesName = "";
		if (!StringUtil.isEmpty(usesString)) {
			String user[] = usesString.split(";");
			for (int i = 0; i < user.length; i++) {
				String press = "";
				String pressName = "";
				String userIds[] = user[i].split(":");
				if (!StringUtil.isEmpty(userIds[1])) {
					Users users = depAndUserHolder.usersService.findById(userIds[1]);
					pressName = users.getUname();
				}
				press = userIds[0];
				usesName += press + ":" + pressName + ";";
			}
		}
		return usesName;
	}
    
    //审批节点用户id拼接字符串
    public static String getApproveUserTaskInfoString(String userId, String processInstanceId) {
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) depAndUserHolder.repositoryService)
                .getDeployedProcessDefinition(processInstanceId);
        Map<String, TaskDefinition> taskDefinitions = processDefinitionEntity.getTaskDefinitions();
        String definitions = "";
        Map<String, Object> dataResult = DepAndUserHolder.getApproveUserInfo(userId, Consts.GUID);
        if (dataResult != null && dataResult.size() > 0) {
            Users userLeader = (Users) dataResult.get("approveLeader");
            Users userManage = (Users) dataResult.get("approveManage");
            for (String key : taskDefinitions.keySet()) {
                String TaskUid = "";
                if ("process".equals(key)) {
                    // 发起人
                    TaskUid = key + ":" + userId + ";";
                } else if ("leader_approve".equals(key) && userLeader != null) {
                    TaskUid = key + ":" + userLeader.getUserId() + ";";
                } else if ("manage_approve".equals(key) && userManage != null) {
                    TaskUid = key + ":" + userManage.getUserId() + ";";
                }
                definitions = definitions + TaskUid;
            }
        }
        return definitions;
    }

    /**
     * 根据用户获取后面所有审批人员信息：当前所在机构没有总经理，则选择父机构总经理作为审批人员
     */
    public static Map<String, Object> getApproveUserInfo(String userId, String guid) {
        Map<String, Object> data = new HashMap<String, Object>();
        // 获取用户权限最高部门
        String depId = "";
        Department department = getUserMaxAuthDep(userId, guid);
        if (department != null) {
            depId = department.getDepId();
        }
        // 该机构下的所有角色(不包含下级)
        List<Roles> roleList = depAndUserHolder.rolesService.findRolesByDepId(depId, Consts.GUID);
        // 总经理角色id
        String manageId = "";
        // 部门领导角色id
        String depLeaderId = "";

        if (roleList != null && roleList.size() > 0) {
            for (int i = 0; i < roleList.size(); i++) {
                Roles role = roleList.get(i);
                if (role.getRoleCode().equals("ROLE_MANAGE")) {
                    manageId = role.getRoleId();
                } else if (role.getRoleCode().equals("ROLE_DEP_LEADER")) {
                    depLeaderId = role.getRoleId();
                }
            }
        }
        List<Users> userList = null;
        // 该用户在该机构下的角色
        List<Roles> userRoleList = DepAndUserHolder.getUserRoleInfo(userId, Consts.GUID, depId);
        if (userRoleList != null && userRoleList.size() > 0) {
            List<String> depList = new ArrayList<String>();
            depList.add(depId);
            // 获取该用户的审批角色
            for (int i = 0; i < userRoleList.size(); i++) {
                Roles role = userRoleList.get(i);
                // 当前角色为普通员工，下一审批角色依次为部门领导,总经理;当前角色为部门领导，下一审批角色为总经理
                if ("ROLE_DEP_STAFF".equals(role.getRoleCode()) || "ROLE_DEP_LEADER".equals(role.getRoleCode())) {
                    if (!StringUtil.isEmpty(depLeaderId) && "ROLE_DEP_STAFF".equals(role.getRoleCode())) {
                        userList = depAndUserHolder.usersService
                                .getUsersQueryResult(0, 0, "", "", depList, depLeaderId, Consts.GUID).getRows();
                        if (userList != null && userList.size() > 0) {
                            data.put("approveLeader", userList.get(0));
                        }
                    }
                    if (!StringUtil.isEmpty(manageId)) {
                        userList = depAndUserHolder.usersService
                                .getUsersQueryResult(0, 0, "", "", depList, manageId, Consts.GUID).getRows();
                        if (userList != null && userList.size() > 0) {
                            data.put("approveManage", userList.get(0));
                        }
                    } else {// 当前部门没有总经理，查找上级部门的总经理
                        List<Roles> roleListUpper = depAndUserHolder.rolesService
                                .findRolesByDepId(department.getUpperId(), Consts.GUID);
                        if (roleListUpper != null && roleListUpper.size() > 0) {
                            List<String> depListUpper = new ArrayList<String>();
                            depListUpper.add(department.getUpperId());
                            for (int j = 0; i < roleListUpper.size(); j++) {
                                Roles roleUpper = roleListUpper.get(j);
                                if (roleUpper.getRoleCode().equals("ROLE_MANAGE")) {
                                    manageId = roleUpper.getRoleId();
                                    // 总经理
                                    userList = depAndUserHolder.usersService
                                            .getUsersQueryResult(0, 0, "", "", depListUpper, manageId, Consts.GUID)
                                            .getRows();
                                    if (userList != null && userList.size() > 0) {
                                        data.put("approveManage", userList.get(0));
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    break;
                }
            }
        }
        return data;
    }

    /**
     * 处理流程节点,查找下一节点处理人id
     */
    public static String getTargetTaskUids(String userAssignee, String jumpTaskKey) {
        String assignee = "";
        String user[] = userAssignee.split(";");
        for (int i = 0; i < user.length; i++) {
            String userIds[] = user[i].split(":");
            if (userIds[0].equals(jumpTaskKey)) {
                assignee = userIds[1];
                break;
            }
        }
        return assignee;
    }

}
